package com.zhika.zishi.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.zhika.zishi.R;
import com.zhika.zishi.adapter.HomepageAdapter;
import com.zhika.zishi.beans.recommend.RecommendBean;
import com.zhika.zishi.beans.recommend.RecommendProblemBean;
import com.zhika.zishi.beans.recommend.RecommendStrategyBean;
import com.zhika.zishi.constant.OthersConstant;
import com.zhika.zishi.customview.ChooseHomepageView;
import com.zhika.zishi.customview.LoadListView;
import com.zhika.zishi.customview.RefreshableView;
import com.zhika.zishi.customview.TitleView;
import com.zhika.zishi.interfaces.ChooseHomepageInterface;
import com.zhika.zishi.interfaces.TitleInterface;
import com.zhika.zishi.internet.GetInternet;
import com.zhika.zishi.util.LogUtil;

import java.util.ArrayList;

/**
 * Created by Michael on 2015/4/8.
 * 推荐主页，也是用户一开始进来时的主页
 */
public class RecommendHomepageActivity extends BaseActivity implements TitleInterface, ChooseHomepageInterface {

    private static final String TAG = "HomepageActivity";

    private static final int STRATEGY_TYPE = 1;

    private static final int PROBLEM_TYPE = 2;

    private RefreshableView refreshableView;

    private LoadListView listView;

    private HomepageAdapter homepageAdapter;

    private ArrayList<RecommendBean> recommendBeanList = new ArrayList<>();

    private ChooseHomepageView chooseHomepageView;

    private TitleView titleView;

    //网络异步请求对象
    private AsyncHttpClient asyncHttpClient;

    //代表刷新的类型：false -- 问题刷新；true -- 攻略刷新
    private boolean type = false;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case STRATEGY_TYPE:
                    Bundle bundle = msg.getData();
                    RecommendStrategyBean bean = (RecommendStrategyBean) bundle.getSerializable("strategy");
                    recommendBeanList.add(0, bean);

                    //完成刷新
                    refreshableView.finishRefreshing();

                    homepageAdapter.notifyDataSetChanged();
                    break;
                case PROBLEM_TYPE:

                    Bundle bundle1 = msg.getData();
                    RecommendProblemBean bean1 = (RecommendProblemBean) bundle1.getSerializable("problem");
                    recommendBeanList.add(0, bean1);

                    //完成刷新
                    refreshableView.finishRefreshing();

                    homepageAdapter.notifyDataSetChanged();
                    break;
                case GetInternet.STRATEGY_HANDLER_WHAT:
                    Bundle strategyBundle = msg.getData();
                    RecommendStrategyBean strategyBean = (RecommendStrategyBean) strategyBundle.getSerializable(GetInternet.STRATEGY_BUNDLE);
                    recommendBeanList.add(0, strategyBean);

                    //完成刷新
                    refreshableView.finishRefreshing();

                    homepageAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homepage_layout);

//        addTestData();

        initView();

        //第一次进入推荐首页，主动调用接口获取推荐攻略
        GetInternet.getRecommendStrategy(handler);
    }

    /**
     * 初始化界面的控件
     */
    private void initView() {

        //初始化异步请求对象
        asyncHttpClient = new AsyncHttpClient();

        listView = (LoadListView) findViewById(R.id.homepage_list_view);
        homepageAdapter = new HomepageAdapter(this, recommendBeanList);
        listView.setAdapter(homepageAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //隐藏弹出框
                chooseHomepageView.setVisibility(View.GONE);

                RecommendBean bean = recommendBeanList.get(position);
                String type = bean.getHomepageType();
                //攻略
                if (type.equals("strategy")) {
                    itemStrategyListener();
                }

                //问题
                else {
                    itemProblemListener();
                }
            }
        });
        listView.setInterface(new LoadListView.ILoadListener() {
            @Override
            public void onLoad() {

            }
        });

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                chooseHomepageView.setVisibility(View.GONE);
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        refreshableView = (RefreshableView) findViewById(R.id.homepage_refresh_view);
        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                if (type) {
                    refreshStrategyListener();
                    type = false;
                } else {
                    refreshProblemListener();
                    type = true;
                }
            }
        }, OthersConstant.HOMEPAGE_REFRESH);
        chooseHomepageView = (ChooseHomepageView) findViewById(R.id.homepage_choose_homepage_view);
        chooseHomepageView.setChooseHomepageInterface(this);

        titleView = (TitleView) findViewById(R.id.homepage_title_view);
        titleView.setTitleViewInterface(this);

        GetInternet.getRecommendStrategy(handler);

    }

    private void addTestData() {

        RecommendStrategyBean bean = new RecommendStrategyBean();
        bean.setHomepageType("strategy");
        bean.setHobbyStr("社交");
        bean.setStrategy("攻略标题攻略标题攻略标题");
        bean.setContentStr("攻略内容攻略内容攻略内容攻略内容攻略内容攻略内容攻略内容");
        bean.setPictureUrlStr("ddd");
        bean.setCommentNumStr("44");
        bean.setCollectNumStr("22");
        bean.setLikeNumStr("111");


        recommendBeanList.add(bean);

    }

    /**
     * listView的item的点击事件：攻略
     */
    private void itemStrategyListener() {

        LogUtil.e(TAG, "攻略点击事件");
        Intent intent = new Intent(RecommendHomepageActivity.this, StrategyDetailsActivity.class);
        startActivity(intent);

    }

    /**
     * listView的item的点击事件：问题
     */
    private void itemProblemListener() {

        LogUtil.e(TAG, "问题点击事件");
        Intent intent = new Intent(RecommendHomepageActivity.this, ProblemDetailsActivity.class);
        startActivity(intent);
    }

    @Override
    public void leftTitleListener() {
        Intent intent = new Intent(RecommendHomepageActivity.this, MySelfInfoActivity.class);
        startActivity(intent);
    }

    @Override
    public void middleTitleListener() {
        Toast.makeText(RecommendHomepageActivity.this, "中间按钮的点击事件", Toast.LENGTH_SHORT).show();
        chooseHomepageView.setVisibility(View.VISIBLE);

    }

    @Override
    public void rightTitleListener() {
        Intent intent = new Intent(RecommendHomepageActivity.this,SearchActivity.class);
        startActivity(intent);
    }

    /**
     * 好友动态的点击事件
     */
    @Override
    public void firstHomepageTextListener() {
        Intent intent = new Intent(RecommendHomepageActivity.this, FriendsDynamicActivity.class);
        startActivity(intent);
        chooseHomepageView.setVisibility(View.GONE);
    }

    /**
     * 频道的点击事件
     */
    @Override
    public void secondHomepageTextListener() {
        Intent intent = new Intent(RecommendHomepageActivity.this, ChannelActivity.class);
        startActivity(intent);
        chooseHomepageView.setVisibility(View.GONE);
    }


    /**
     * 下拉刷新：攻略更新
     */
    private void refreshStrategyListener() {
        String url = "";

        /**
         * 真正的网络请求数据
         */
//        asyncHttpClient.get(HomepageActivity.this,url,new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                //从服务端返回的数据
//                String jsonData = new String(responseBody);
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//
//            }
//        });

        RecommendStrategyBean bean = new RecommendStrategyBean();
        bean.setHomepageType("strategy");
        bean.setHobbyStr("更新");
        bean.setStrategy("攻略更新");
        bean.setContentStr("攻略内容更新攻略内容更新攻略内容更新");
        bean.setPictureUrlStr("dd");
        bean.setCommentNumStr("g评论");
        bean.setCollectNumStr("g收藏");
        bean.setLikeNumStr("g关注");

        Message message = Message.obtain();
        Bundle bundle = new Bundle();
        bundle.putSerializable("strategy",bean);
        message.setData(bundle);
        message.what = STRATEGY_TYPE;
        handler.sendMessage(message);

    }

    /**
     * 下拉刷新：问题的更新
     */
    private void refreshProblemListener() {
        String url = "";

        /**
         * 真正的网络请求数据
         */
//        asyncHttpClient.get(HomepageActivity.this,url,new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                //从服务端返回的数据
//                String jsonData = new String(responseBody);
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//
//            }
//        });

        RecommendProblemBean bean = new RecommendProblemBean();
        bean.setHomepageType("problem");
        bean.setHobbyStr("问题更新");
        bean.setProblemStr("问题内容更新");
        bean.setCollectNumStr("44");
        bean.setCommentNumStr("11");

        Message message = Message.obtain();
        Bundle bundle = new Bundle();
        bundle.putSerializable("problem",bean);
        message.setData(bundle);
        message.what = PROBLEM_TYPE;
        handler.sendMessage(message);


    }


    /**
     * 加载更多事件的真正任务
     */
    private class OnLoadTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            //加载完成
            listView.loadComplete();

            //通知ListView更新界面
            homepageAdapter.notifyDataSetChanged();
        }
    }
}
